<?php
namespace app\nadmin\controller;
use think\Controller;
use think\facade\Request;
use think\facade\Session;
use think\facade\Cookie;
/**
 * 检测是否登陆，并返回权限 钩子
 */

class Islogin extends Controller
{
    public function run()
    {
        $module = request()->module();
        $controller = request()->controller();  //当前访问控制器
        $action = request()->action(); //当前访问方法

        //检测cookie中的用户数据
        $info = $this->checkInfo();
        if(!$info){
            $this->redirectLogin();
        }
        //检测token
        if(!$this->checkToken($info['id']))
        {
            $this->redirectLogin();
        }
        //检测权限
        $power = $this->checkPower($info['id']);
        $doNotCheckMenu = Session::get("doNotCheckMenu_".$info['id']);

        if(is_array($power))
        {
            $nowURI = strtolower($module.'/'.$controller.'/'.$action);
            //var_dump($nowURI);var_dump($power);var_dump($doNotCheckMenu);die;
            if(!in_array($nowURI,$power) && !in_array($nowURI,$doNotCheckMenu))
            {
                if(Request::instance()->isAjax())
                {
                    echo json_encode(["msg"=>"木有权限哦","status"=>0]);die;  //ajax请求返回json
                }else{
                    //非ajax请求，重定向
                    echo "<script>window.location.href='nadmin.php?s=nadmin/sundry/nopower';</script>";
                    die;
                }

            }

        }else{
            $this->redirectLogin();
        }

    }

    //检测cookie中的用户数据
    protected function checkInfo()
    {
        $adminerId = Cookie::get("adminerId");
        if(empty($adminerId))
        {
            return false;
        }
        $info = Session::get("adminerInfo_".$adminerId);
        return $info;
    }

    //检测token  $id 管理员id，return bool
    protected function checkToken($id)
    {
        if(!(is_numeric($id) && strpos($id,'.') === false && $id > 0))
        {
            return false;
        }

        $token = Session::get("adminerToken_".$id);
        //无token
        if(!$token)
        {
            return false;
        }

        //判断token是否异常
        $tokenNow = createAdminerToken($id);
        if($tokenNow === $token)
        {
            return true;
        }
        return false;
    }

    //检测权限 $id 管理员id , return mixed
    protected function checkPower($id)
    {
        if(!(is_numeric($id) && strpos($id,'.') === false && $id > 0))
        {
            return false;
        }
        $power = Session::get("adminerPower_".$id);
        if($power)
        {
            return $power;
        }
        return false;
    }

    protected function redirectLogin()
    {
        $str = "<script>parent.window.location.href='nadmin.php?s=nadmin/Login/index';</script>";
        echo $str;
        die;
    }
}